package com.logic.landseaserver.service.callback;

import java.util.Date;
import java.util.HashMap;

import com.logic.landseaserver.service.IBillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.logic.landseaserver.common.LandeaConstants.QueryUesdCodeType;
import com.logic.landseaserver.common.LandseaErrorMessageEnum;
import com.logic.landseaserver.common.enums.BillStatusEnum;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.models.authcode.service.AuthCodeService;
import com.logic.landseaserver.models.payment.service.PaymentService;
import com.logic.landseaserver.service.IContractService;
import com.logic.landseaserver.ws.dto.BillDTO;

/**
 *
 * 项目名称：system-server</br>
 * 类名称：FirstBillBusinessService</br>
 * 类描述：首付款回调业务逻辑处理</br>
 * 创建人：Tony</br>
 * 创建时间：2017年7月5日 下午4:05:56</br>
 * @version 1.0
 *
 */
@Service("WebankCallBack_BT1")
public class FirstBillBusinessService implements IWebankCallbackHandler
{
    private static final Logger LOG = LoggerFactory.getLogger(FirstBillBusinessService.class);
    
    @Autowired
    private PaymentService paymentService;
    
    @Autowired
    private IContractService contractService;
    
    @Autowired
    private AuthCodeService authCodeService;

    @Autowired
    private IBillService billService;
    
    @Override
    public Object process(HashMap<String, Object> param)
        throws LandseaException
    {
        LOG.info("首期款业务处理start");
        Integer billId = (Integer)param.get("billId");
        
        try
        {
            Double currentPayMoney = (Double)param.get("currentPayMoney");
            Date payTime = (Date)param.get("payTime");

            BillDTO bill = paymentService.updateBillStateAndMoney(billId, currentPayMoney);
            Integer contractId = bill.getContractId();
            
            if (BillStatusEnum.BIST2.getCode().equals(bill.getBillStatus()))
            {
                contractService.updateAfterPay(contractId, bill.getId(), payTime);
               // TOOD by Junny
                billService.updateMontlyOrgContract(contractId,billId);
            }
            else
            {
                LOG.info("WebankCallBack_BT1 |首付款未完全支付，不能修改合同状态|" + param.toString());
            }
            
            // 更新授权码为已使用状态
            authCodeService.updateCouponStatusAfterPay(QueryUesdCodeType.CONTRACT, contractId);
        }
        catch (Exception e)
        {
            LOG.error("WebankCallBack_BT1 |handle callback event failed.", e);
            throw LandseaException.createException(LandseaErrorMessageEnum.WEBANK_CALLBACK_BT1_PARAM_ERROR, e);
        }
        LOG.info("首期款业务处理end");
        return null;
    }
}
